package com.pms.util;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.UploadFileRequest;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;

/**
 * 阿里云 OSS文件类
 *
 * @author YuanDuDu
 */
public class OSSClientUtil {

	Log log = LogFactory.getLog(OSSClientUtil.class);
	// endpoint以杭州为例，其它region请按实际情况填写
//	public static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";

	public static String endpoint = "http://upimg.ahmkj.cn";
	// accessKey
	public static String accessKeyId = "LTAIveMr8nLjAomt";
	public static String accessKeySecret = "p4MfZNsxyeFbEqBcdHYwkANDBM99Pf";
	// 空间
	private String bucketName = "hmkjpublicimg";
	// 文件存储目录
	private String filedir = "pms/";

	private static OSSClient ossClient;

	public OSSClientUtil() {
		ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	}

	/**
	 * 初始化
	 */
	public static void init() {
		ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	}

	/**
	 * 销毁
	 */
	public static void destory() {
		ossClient.shutdown();
	}

	/**
	 * 上传图片
	 *
	 * @param url
	 * @throws Exception
	 */
	public void uploadImg2Oss(String url) throws Exception {
		File fileOnServer = new File(url);
		FileInputStream fin;
		try {
			fin = new FileInputStream(fileOnServer);
			String[] split = url.split("/");
			this.uploadFile2OSS(fin, split[split.length - 1]);
		} catch (FileNotFoundException e) {
			throw new Exception("图片上传失败");
		}
	}

	public String uploadImg2Oss(MultipartFile file) throws Exception {
		if (file.getSize() > 1024 * 1024) {
			throw new Exception("上传图片大小不能超过1M！");
		}
		String originalFilename = file.getOriginalFilename();
		String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
		Random random = new Random();
		String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
		try {
			InputStream inputStream = file.getInputStream();
			this.uploadFile2OSS(inputStream, name);
			return name;
		} catch (Exception e) {
			throw new Exception("图片上传失败");
		}
	}

	/**
	 * 获得图片路径
	 *
	 * @param fileUrl
	 * @return
	 */
	public String getImgUrl(String fileUrl) {
		if (!StringUtils.isEmpty(fileUrl)) {
			String[] split = fileUrl.split("/");
			return this.getUrl(this.filedir + split[split.length - 1]);
		}
		return null;
	}

	/**
	 * 上传到OSS服务器 如果同名文件会覆盖服务器上的
	 *
	 * @param instream
	 *            文件流
	 * @param fileName
	 *            文件名称 包括后缀名
	 * @return 出错返回"" ,唯一MD5数字签名
	 */
	public String uploadFile2OSS(InputStream instream, String fileName) {
		String ret = "";
		try {
			// 创建上传Object的Metadata
			ObjectMetadata objectMetadata = new ObjectMetadata();
			objectMetadata.setContentLength(instream.available());
			// objectMetadata.setCacheControl("no-cache");
			// objectMetadata.setHeader("Pragma", "no-cache");
			// objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
			// objectMetadata.setContentDisposition("inline;filename=" +
			// fileName);
			// 上传文件
			PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
			
			
			ret = putResult.getETag();
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			e.printStackTrace();
		} finally {
			try {
				if (instream != null) {
					instream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	/**
	 * Description: 判断OSS服务文件上传时文件的contentType
	 *
	 * @param FilenameExtension
	 *            文件后缀
	 * @return String
	 */
	public static String getcontentType(String FilenameExtension) {
		if (FilenameExtension.equalsIgnoreCase("bmp")) {
			return "image/bmp";
		}
		if (FilenameExtension.equalsIgnoreCase("gif")) {
			return "image/gif";
		}
		if (FilenameExtension.equalsIgnoreCase("jpeg") || FilenameExtension.equalsIgnoreCase("jpg")
				|| FilenameExtension.equalsIgnoreCase("png")) {
			return "image/jpeg";
		}
		if (FilenameExtension.equalsIgnoreCase("html")) {
			return "text/html";
		}
		if (FilenameExtension.equalsIgnoreCase("txt")) {
			return "text/plain";
		}
		if (FilenameExtension.equalsIgnoreCase("vsd")) {
			return "application/vnd.visio";
		}
		if (FilenameExtension.equalsIgnoreCase("pptx") || FilenameExtension.equalsIgnoreCase("ppt")) {
			return "application/vnd.ms-powerpoint";
		}
		if (FilenameExtension.equalsIgnoreCase("docx") || FilenameExtension.equalsIgnoreCase("doc")) {
			return "application/msword";
		}
		if (FilenameExtension.equalsIgnoreCase("xml")) {
			return "text/xml";
		}
		return "image/jpeg";
	}

	/**
	 * 获得url链接
	 *
	 * @param key
	 * @return
	 */
	public String getUrl(String key) {
		// 设置URL过期时间为10年 3600l* 1000*24*365*10
		Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
		// 生成URL
		URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
		if (url != null) {
			return url.toString();
		}
		return null;
	}

	@SuppressWarnings("unused")
	private static void uploadFile(OSSClient client, String bucketName, String Objectkey, String filename)
			throws OSSException, com.aliyun.oss.ClientException, FileNotFoundException {
		File file = new File(filename);
		ObjectMetadata objectMeta = new ObjectMetadata();
		objectMeta.setContentLength(file.length());
		// 判断上传类型，多的可根据自己需求来判定
		if (filename.endsWith("xml")) {
			objectMeta.setContentType("text/xml");
		} else if (filename.endsWith("jpg")) {
			objectMeta.setContentType("image/jpeg");
		} else if (filename.endsWith("png")) {
			objectMeta.setContentType("image/png");
		}

		InputStream input = new FileInputStream(file);
		client.putObject(bucketName, Objectkey, input, objectMeta);
	}
	
	/**
	 * app 删除阿里服务器图片
	 * 
	 * @param imgUrl
	 */
	public static void deleteImg(String imgUrl) {
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			// 删除Object
			String urlc = imgUrl.substring(imgUrl.lastIndexOf("/appdata") + 1);
			ossClient.deleteObject("hmkjpublicimg", urlc);
			/**
			 * 这儿暂时没有关闭阿里图片服务器连接,打开报线程错误
			 */
			ossClient.shutdown();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
//	public static void main(String[] args) {
//		deleteImg("http://upimg.ahmkj.cn/appdata//STORAGE/emulated/0/DCIM/Camera/LSQ20170428174704992.jpg.png");
//	}

	
	/**
	 * 上传视频文件
	 * @param fileName  文件名
	 * @param fileDatas  文件地址
	 * @return
	 */			
	public String uploadVideoFile(String fileName,String fileDatas) {
			String ret = "";
			 PutObjectResult name = ossClient.putObject("hmkjpublicimg", filedir + fileName,new File(fileDatas));
			 ret = name.getETag();
		return ret;
	}
	
	
	
	
	public Object uploadVideoFile1(String bb,String fname) {
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient("http://upimg.ahmkj.cn", accessKeyId, accessKeySecret);
		// 设置断点续传请求
		UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName,filedir + fname);
		// 指定上传的本地文件
		uploadFileRequest.setUploadFile(bb);
		// 指定上传并发线程数
		uploadFileRequest.setTaskNum(5);
		// 指定上传的分片大小
		uploadFileRequest.setPartSize(1 * 1024 * 1024);
		// 开启断点续传
		uploadFileRequest.setEnableCheckpoint(true);
		
		// 断点续传上传
		try {
			JSONObject json = JSONObject.fromObject(JSON.toJSONString(ossClient.uploadFile(uploadFileRequest)));
			return json;
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 关闭client
		ossClient.shutdown();
		return null;
	}

	/**
	 * 删除阿里云图片
	 * @param OldimgUrl
	 */
	public static void deleteOldimgUrl(String OldimgUrl) {
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
		String urlc = OldimgUrl.substring(OldimgUrl.lastIndexOf("/pms") + 1);
		ossClient.deleteObject("hmkjpublicimg", urlc);
		// 关闭client
		ossClient.shutdown();
	}





}